#include "UdpClient.hpp"
#include<iostream>
#include<string.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<cstdlib>
#include "Comm.hpp"
#include <thread>


int sockfd = -1;
void Recver()
{

    while(1)
    {
        sockaddr temp;
        socklen_t len = sizeof(temp);
        char buffer[1024];
        int n = ::recvfrom(sockfd, buffer, sizeof(buffer)-1, 0, (sockaddr*)(&temp), &len);
        if(n>0)
        {
            buffer[n] = '\0';
            std::cout<<buffer<<std::endl;
        }
    }
 
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        std::cerr<<"Usage:"<<argv[0]<< "serverip serverport" <<std::endl;
        exit(1);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    //1创建socket
    sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        std::cerr<<"socket error"<<std::endl;
        DIE(SOCKET_ERR);
    }

    //填充server
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = ::htons(serverport);
    server.sin_addr.s_addr = ::inet_addr(serverip.c_str());

    //创建线程接受消息
    std::thread t(Recver);
    //2.clientdone
    while(1)
    {
        std::cout<<"Please Enter"<<std::endl;
        std::string message;
        std::getline(std::cin, message);
        //客户端client不需要自己显式调用bind，由OS自动调用
        int n = ::sendto(sockfd, message.c_str(), message.size(),0, (sockaddr*)(&server), sizeof(server));
        (void)n;
    }
    return 0;
}